import { ref, type Ref } from "vue";
import { useThrottle, type ThrottleOptions } from "../useThrottle";

type Position = { left: number; top: number };

export interface Result {
    position: Ref<Position>,
    remove: () => void
}

/**
 * 监听元素的滚动位置。
 * @param target 可选参数：监听滚动的元素
 * @param options 可选参数：wait时间间隔，leading第一次是否执行, trailing 最后一次是否执行
 * @returns { position: Ref<{left, top}>, remove: () => void }
 */
export const useScroll = function (target?: Element | Document, options?: ThrottleOptions): Result {

    const position = ref<Position>({left: 0, top: 0})

    const { run: updatePosition } = useThrottle(function () {

        if (target === document) {
          if (document.scrollingElement) {
            position.value = {
              left: document.scrollingElement.scrollLeft,
              top: document.scrollingElement.scrollTop,
            };
          } else {
            position.value = {
              left: Math.max(
                window.pageXOffset,
                document.documentElement.scrollLeft,
                document.body.scrollLeft,
              ),
              top: Math.max(
                window.pageYOffset,
                document.documentElement.scrollTop,
                document.body.scrollTop,
              ),
            };
          }
        } else {
            position.value = {
                left: (target as Element).scrollLeft,
                top: (target as Element).scrollTop,
            };
        }

    }, {
      wait: 200,
      leading: true,
      trailing: true,
      ...options
    });
  
    if (target) {
      updatePosition()
      target.addEventListener('scroll', updatePosition);
    }

    function remove () {
        target?.removeEventListener('scroll', updatePosition);
    }

  return { position, remove };
  
}